package com.taptech.doufu.ui.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;

import androidx.appcompat.app.AppCompatDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.Selection;
import android.text.SpanWatcher;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.BackgroundColorSpan;
import android.util.AndroidRuntimeException;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.iyao.eastat.NoCopySpanEditableFactory;
import com.taptech.doufu.bean.AuthorInfoBean;
import com.taptech.doufu.bean.base.BaseResponseBean;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.ui.adapter.EditNovelThemeAdapter;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.SharedPreferencesKey;
import com.taptech.doufu.ui.adapter.PunctuationAdapter;
import com.taptech.doufu.ui.dialog.DoubleBtnTiptDialog;
import com.taptech.doufu.ui.dialog.NovelCreateSentTimeDialog;
import com.taptech.doufu.ui.dialog.PublishTipSingleBtnDialog;
import com.taptech.doufu.event.EventBusBackup;
import com.taptech.doufu.event.EventBusRefreshData;
import com.taptech.doufu.manager.NovelEditManager;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.bean.NovelEditModel;
import com.taptech.doufu.bean.NovelPublicTipsGson;
import com.taptech.doufu.bean.RiskWordGson;
import com.taptech.doufu.umeng.push.InAppMessageKey;
import com.taptech.doufu.umeng.push.PushManager;
import com.taptech.doufu.sdk.universalimageloader.core.ImageLoader;
import com.taptech.doufu.sdk.universalimageloader.core.ImageLoaderConfiguration;
import com.taptech.doufu.util.AesUtil;
import com.taptech.doufu.util.ScreenBrightnessUtil;
import com.taptech.doufu.util.ScreenUtil;
import com.taptech.doufu.util.ScreenUtil2;
import com.taptech.doufu.util.SoftKeyboardUtil;
import com.taptech.doufu.util.StringUtil;
import com.taptech.doufu.R;
import com.taptech.doufu.bean.HomeTopBean;
import com.taptech.doufu.bean.NovelCreateBean;
import com.taptech.doufu.bean.NovelDraftBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.ui.dialog.DoubleBtnLongTextDialog;
import com.taptech.doufu.ui.dialog.SingleBtnDialog;
import com.taptech.doufu.bean.TipInfo;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.listener.ResultTipListener;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.services.personalcenter.WeiboService;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.services.NovelCreateServices;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.GlideUtil;
import com.taptech.doufu.util.SharedPreferenceUtil;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.util.TimeDateFunction;
import com.taptech.doufu.util.TimeUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;
import com.taptech.doufu.ui.view.PerformEdit;
import com.taptech.doufu.ui.view.ProtocolDialog;
import com.taptech.doufu.ui.view.ResizeLayout;
import com.taptech.doufu.ui.view.WaitDialog;
import com.taptech.doufu.ui.view.theme.editnovel.EditNovelTheme;
import com.taptech.doufu.ui.view.theme.editnovel.EditNovelThemeHelper;
import com.taptech.doufu.ui.view.theme.ThemeType;
import com.taptech.doufu.weex.notification.QLXNotificationCenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import rx.Observable;

public class NovelCreateContentTosActivity extends DiaobaoBaseActivity implements HttpResponseListener, View.OnClickListener, TextWatcher,EditNovelThemeAdapter.OnClickItem{
    public static final String SAY_CONTENT = "SAY_CONTENT";
    public static final int RESULT_CODE_SAY_CONTENT = 52402;// 作者有话说页面结果码
    public static final int REQUEST_CODE_SAY_CONTENT = 52401;// 作者有话说页面请求码


    private static final String SP_KEY_NOVEL_EDIT_GUIDE = "novel_edit_guide";
    private EditText edTitle, edContent;
    private HomeTopBean bean;
    private TextView tvHint;

    private NovelDraftBean novelBean;
    private HomeTopBean contentBean;
    private WaitDialog dialog;
    private int nvoelFlag = 0;// 章节类型
    private String mContent, mTitle, mAuthorSay;

    private boolean isAutoSava = true;// 是否自动保存
    private String initTitle, initContent, initAuthorSay,timer_note;// 初始标题、内容、作者的话
    private int idChecked = 0;  //是否实名认证
    private boolean needSetAuthorInfo = false;  //需要弹出预留信息框
    private WaitDialog contentWaitDialog;
    private ImageView imgHead;// 作者头像
    private ArrayList<String> novelids;// 小说id集合
    protected ImageLoader imageLoader = null;
    private ImageLoaderConfiguration configuration;
    private Timer timer;
    private ResizeLayout rootLayout;
    private View bottomBar, lineBottom,lineTitle,lineContent;
    private ScrollView svContent;
    private boolean isedContentFocus;
    private boolean isSoftInputMode;
    private boolean isTimeSent = false;


    private PerformEdit mPerformEdit;  //文本编辑器撤销和重做工具类
    private RelativeLayout rlNormalTitleBar,rlEditTitleBar;
    private ImageView ivRedo,ivUndo;
    private View layPunctuation;
    private ImageView ivHidePunctuation;
    private View linePunctuation ;


    private boolean canUndo,canRedo;

    private EditNovelThemeAdapter adapter;
    private RelativeLayout rlTheme;
    private LinearLayout llLightAdd; //增加亮度
    private LinearLayout llLightSub; //降低亮度
    private LinearLayout llSysLight; //系统亮度
    private TextView tvSysLight;
    private LinearLayout llFontSizeAdd; //增加字体大小
    private LinearLayout llFontSizeSub; //减小字体大小
    private RecyclerView recycleView;//主题选择栏
    private boolean isSysLight = true;
    private SeekBar seekbarFontSize;  //字体大小进度条
    private SeekBar seekbarLight;  //亮度进度条
    private ImageView ivLightSub,ivLightAdd,ivFontSizeSub,ivFontSizeAdd;
    private RelativeLayout titleLayout;
    private LinearLayout llParent;
    private LinearLayout llDayAndNight,llThemeSet,llHistory;
    private View muneScreen,topVerticalLine;
    private ImageView ivBack,ivFormat,ivSave,ivClock,ivNight,ivSet,ivHistory,ivSensitive;
    private TextView tvSend,tvContentCount, tvAuthorSay,tvNight,tvSet,tvHistory;

    private String lastSaveTitle,lastSaveContent,lastSaveAuthorSay; //用于保存草稿去重

    private String lastTempTitle,lastTempContent,lastTempAuthorSay; //用于临时存稿去重
    private long localDBid;
    private boolean isUnSync = false;
    private boolean isClosePage = false;

    private RelativeLayout rlChildGuide1,rlChildGuide2,rlGuide;
    private TextView tvSure;
    private String publish;     //发布作品后的临时审核中的状态 值为"1"时表示该章节属于这种临时状态，身在草稿列表，却是已发布章节
    private String chapterId;

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void onResetBackup(EventBusBackup event) {
        if (event != null && event.getTag().equals(EventBusBackup.tag) && event.getModel()!=null) {
            resetBackup(event.getModel());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_novel_create_content_tos);
        EventBus.getDefault().register(this);
        initUI();
        initData();
        setListen();
        initWeiboView();
        ctrlWaitDialong(true);

        Serializable serializable = getIntent().getSerializableExtra(Constant.DATA);
        if (serializable != null) {
            initData(serializable, nvoelFlag);
        }
        setPageTheme(EditNovelThemeHelper.getEditNovelTheme());
        publish= getIntent().getStringExtra("publish");
        if (nvoelFlag == NovelEditManager.NOVEL_SECTION||"1".equals(publish)) {
            ivSave.setVisibility(View.GONE);
            ivClock.setVisibility(View.GONE);
        }else{
            ivSave.setVisibility(View.VISIBLE);
            ivClock.setVisibility(View.VISIBLE);
        }
        getTips();
        getSensitiveWordList();
        PushManager.getInstance().inAppMessage(this,InAppMessageKey.WRITE);
    }


    /**
     * 初始化UI
     */
    private void initUI() {
        llHistory = (LinearLayout) findViewById(R.id.llHistory);
        llHistory.setOnClickListener(this);
        tvHistory = (TextView) findViewById(R.id.tvHistory);
        ivHistory = (ImageView) findViewById(R.id.ivHistory);
        tvSend = (TextView) findViewById(R.id.tvSend);
        tvNight = (TextView) findViewById(R.id.tvNight);
        tvSet = (TextView) findViewById(R.id.tvSet);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        ivFormat = (ImageView) findViewById(R.id.ivFormat);
        ivSensitive = (ImageView) findViewById(R.id.ivSensitive);
        ivSave = (ImageView) findViewById(R.id.ivSave);
        ivClock = (ImageView) findViewById(R.id.ivClock);
        ivNight = (ImageView) findViewById(R.id.ivNight);
        ivSet = (ImageView) findViewById(R.id.ivSet);
        topVerticalLine = findViewById(R.id.topVerticalLine);
        lineBottom = findViewById(R.id.lineBottom);
        lineContent = findViewById(R.id.lineContent);
        lineTitle = findViewById(R.id.lineTitle);
        muneScreen = findViewById(R.id.muneScreen);
        muneScreen.setOnClickListener(this);
        llThemeSet = (LinearLayout) findViewById(R.id.llThemeSet);
        llThemeSet.setOnClickListener(this);
        llDayAndNight = (LinearLayout) findViewById(R.id.llDayAndNight);
        llDayAndNight.setOnClickListener(this);
        llParent = (LinearLayout) findViewById(R.id.llParent);
        titleLayout = (RelativeLayout) findViewById(R.id.titleLayout);
        ivLightSub = (ImageView) findViewById(R.id.ivLightSub);
        ivLightAdd = (ImageView) findViewById(R.id.ivLightAdd);
        ivFontSizeSub = (ImageView) findViewById(R.id.ivFontSizeSub);
        ivFontSizeAdd = (ImageView) findViewById(R.id.ivFontSizeAdd);
        rlTheme = (RelativeLayout) findViewById(R.id.rlTheme);
        llLightAdd = (LinearLayout) findViewById(R.id.llLightAdd);
        llLightSub = (LinearLayout) findViewById(R.id.llLightSub);
        llSysLight = (LinearLayout) findViewById(R.id.llSysLight);
        llFontSizeAdd = (LinearLayout) findViewById(R.id.llFontSizeAdd);
        llFontSizeSub = (LinearLayout) findViewById(R.id.llFontSizeSub);
        tvSysLight = (TextView) findViewById(R.id.tvSysLight);
        recycleView = (RecyclerView) findViewById(R.id.recycleView);
        seekbarLight = (SeekBar) findViewById(R.id.seekbarLight);
        seekbarFontSize = (SeekBar) findViewById(R.id.seekbarFontSize);

        rlGuide = (RelativeLayout)findViewById(R.id.rlGuide);
        rlChildGuide1 = (RelativeLayout) findViewById(R.id.rlChildGuide1);
        rlChildGuide2 = (RelativeLayout) findViewById(R.id.rlChildGuide2);
        tvSure = (TextView) findViewById(R.id.tvSure);
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rlChildGuide1.setVisibility(View.GONE);
                rlChildGuide2.setVisibility(View.VISIBLE);
            }
        });
        rlChildGuide2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rlGuide.setVisibility(View.GONE);
                DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SP_KEY_NOVEL_EDIT_GUIDE,false,NovelCreateContentTosActivity.this);
            }
        });

        boolean isShowGuide = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(SP_KEY_NOVEL_EDIT_GUIDE, this, true);
        if (isShowGuide){
            rlGuide.setVisibility(View.VISIBLE);
            rlChildGuide1.setVisibility(View.VISIBLE);
            rlChildGuide2.setVisibility(View.GONE);
        }else{
            rlGuide.setVisibility(View.GONE);
        }

        tvHint = (TextView) findViewById(R.id.tvHint);
        ivRedo = (ImageView) findViewById(R.id.ivRedo);
        ivUndo = (ImageView) findViewById(R.id.ivUndo);
        rlNormalTitleBar = (RelativeLayout) findViewById(R.id.rlNormalTitleBar);
        rlEditTitleBar = (RelativeLayout) findViewById(R.id.rlEditTitleBar);
        tvHint.setText("\u3000\u3000输入小说内容：(10000字以内)");
        edTitle = (EditText) findViewById(R.id.activity_novel_create_content_ed_title);
        edContent = (EditText) findViewById(R.id.activity_novel_create_content_ed_content);
        edContent.setEditableFactory(new NoCopySpanEditableFactory(new MySpanWatcher()));
        edContent.setText("\u3000\u3000");
        edContent.addTextChangedListener(this);
        edContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED && event.getAction() == KeyEvent.ACTION_UP) {
                    edContent.getText().insert(edContent.getSelectionStart(),"\n\u3000\u3000");
                }
                return true;
            }
        });
        edContent.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean isfocus) {
                isedContentFocus = isfocus;
                showEdTitle();
                showTitleBar();
            }
        });

        mPerformEdit = new PerformEdit(edContent, new PerformEdit.PerformStateChange() {
            @Override
            public void onRedoStateChange(boolean canChange) {
                canRedo = canChange;
                if (canChange) {
                    ivRedo.setImageResource(EditNovelThemeHelper.getEditNovelTheme().getTopBarTheme().getRedoSelectImage());
                }else{
                    ivRedo.setImageResource(EditNovelThemeHelper.getEditNovelTheme().getTopBarTheme().getRedoImage());
                }
            }

            @Override
            public void onUndoStateChange(boolean canChange) {
                canUndo = canChange;
                if (canChange) {
                    ivUndo.setImageResource(EditNovelThemeHelper.getEditNovelTheme().getTopBarTheme().getUndoSelectImage());
                }else{
                    ivUndo.setImageResource(EditNovelThemeHelper.getEditNovelTheme().getTopBarTheme().getUndoImage());
                }
            }
        });


        imgHead = (ImageView) findViewById(R.id.imgHead);
        rootLayout = (ResizeLayout)findViewById(R.id.novel_create_content_rootlayout);
        bottomBar = findViewById(R.id.bottomBar);
        svContent = (ScrollView) findViewById(R.id.svContent);
        rootLayout.setOnRelativeLayoutResizeListener(new ResizeLayout.OnRelativeLayoutResizeListener() {
            @Override
            public void onResize(boolean flag, int space) {
                isSoftInputMode = flag;
                if(isSoftInputMode){
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            bottomBar.setVisibility(View.GONE);
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
                            params.bottomMargin = ScreenUtil.dip2px(NovelCreateContentTosActivity.this,46);
                            svContent.setLayoutParams(params);
                        }
                    },10);
                }else {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            bottomBar.setVisibility(View.VISIBLE);

                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
                            params.bottomMargin = 0;
                            svContent.setLayoutParams(params);
                        }
                    },100);
                }

                showEdTitle();
            }
        });
        initLayPunctuation();
    }


    private void initLayPunctuation() {
        layPunctuation = findViewById(R.id.layPunctuation);
        ivHidePunctuation = (ImageView) findViewById(R.id.ivHidePunctuation);
        linePunctuation = findViewById(R.id.linePunctuation);
        RecyclerView rvPunctuation = (RecyclerView) findViewById(R.id.rvPunctuation);
        View layHide = findViewById(R.id.layHide);
        layHide.setOnClickListener(v -> SoftKeyboardUtil.hideSoftKeyboard(NovelCreateContentTosActivity.this));
        LinearLayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
        PunctuationAdapter adapter = new PunctuationAdapter(this, (position, title) -> {
            if (edContent.hasFocus()) {
                addPunctuation(edContent,title);
            }else if (edTitle.hasFocus()) {
                addPunctuation(edTitle,title);
            }
        });
        List<String> list = new ArrayList<>();
        list.add("，");
        list.add("。");
        list.add("！");
        list.add("？");
        list.add("：");
        list.add("...");
        list.add("“”");
        list.add("、");
        adapter.setDataList(list);
        rvPunctuation.setLayoutManager(manager);
        rvPunctuation.setAdapter(adapter);
    }

    private void addPunctuation(EditText edText, String punctuation) {
        try {
            int index = edText.getSelectionEnd();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(edText.getText().toString(), 0, index);
            stringBuilder.append(punctuation);
            stringBuilder.append(edText.getText().toString(), index, edText.length());
            edText.setText(stringBuilder);
            if ("“”".equals(punctuation)){
                edText.setSelection(index+1);
            }else{
                edText.setSelection(index+punctuation.length());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void getTips() {
        ApiClient.getInstance().getService().getNovelPublishTips(18)
                .compose(RxJavaHelper.<NovelPublicTipsGson>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<NovelPublicTipsGson>(){
                    @Override
                    public void onNext(NovelPublicTipsGson novelPublicTipsGson) {
                        super.onNext(novelPublicTipsGson);
                        if (novelPublicTipsGson != null && novelPublicTipsGson.getData()!=null) {
                            if (novelPublicTipsGson.getData().getDraft() != null) {
                                timer_note = novelPublicTipsGson.getData().getDraft().getTimer_note();
                            }
                            idChecked = novelPublicTipsGson.getData().getId_checked();
                            needSetAuthorInfo = novelPublicTipsGson.getData().getNeed_contact_info()==1;
                        }
                    }
                });
    }

    private void showEdTitle(){
        if(isSoftInputMode && isedContentFocus){
            edTitle.setVisibility(View.GONE);
            rlEditTitleBar.setVisibility(View.VISIBLE);
            rlNormalTitleBar.setVisibility(View.GONE);
        }else {
            edTitle.setVisibility(View.VISIBLE);
            rlNormalTitleBar.setVisibility(View.VISIBLE);
            rlEditTitleBar.setVisibility(View.GONE);
        }
    }


    private void showTitleBar(){
        if(isedContentFocus){
            rlEditTitleBar.setVisibility(View.VISIBLE);
            rlNormalTitleBar.setVisibility(View.GONE);
        }else {
            rlNormalTitleBar.setVisibility(View.VISIBLE);
            rlEditTitleBar.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        nvoelFlag = getIntent().getIntExtra(Constant.FLAG, -1);
        novelids = getIntent().getStringArrayListExtra("NOVELIDS");
        imageLoader = ImageLoader.getInstance();
        configuration = ImageLoaderConfiguration.createDefault(this);
        imageLoader.init(configuration);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(edTitle.getText().toString()) || TextUtils.isEmpty(edContent.getText().toString())) {
                    return;
                }
                saveTempData();
            }
        }, 10000, 10000);
    }

    /**
     * 初始化微博相关控件
     */
    private void initWeiboView() {
        tvContentCount = (TextView) findViewById(R.id.tvContentCount);
        tvAuthorSay = (TextView) findViewById(R.id.tvAuthorSay);
        tvAuthorSay.setOnClickListener(this);
    }

    private void saveWeiboState() {
        SharedPreferences sharedPreferences = getSharedPreferences("use_weiobo_default_status", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(AccountService.getInstance().getUserUid(), isWeiboSelected);
        editor.commit();
    }

    public void back(View view) {
        if (checkContent()) {
            saveDraftUpdateUI(false);
            finish();
        }
    }


    @Override
    public void onBackPressed() {
        if (checkContent()) {
            saveDraftUpdateUI(false);
            super.onBackPressed();
        }
    }


    private void saveDraftUpdateUI(final boolean isSaveByUser) {
        saveDraft(isSaveByUser, new NovelEditManager.OnResult() {
            @Override
            public void onSuccess() {
                if (nvoelFlag == NovelEditManager.NOVEL_SECTION){
                    Toast.makeText(WeMediaApplication.applicationContext,"修改内容已存入章节“历史”",Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(WeMediaApplication.applicationContext,"保存并同步成功",Toast.LENGTH_LONG).show();
                }
                EventBusRefreshData event = new EventBusRefreshData();
                event.setTag(EventBusRefreshData.tag);
                event.setError(false);
                EventBus.getDefault().post(event);
                if (isSaveByUser) {
                    dimsDialog();
                    finish();
                }
            }

            @Override
            public void onError(String msg) {
                Toast.makeText(WeMediaApplication.applicationContext,"成功保存至本地",Toast.LENGTH_LONG).show();
                EventBusRefreshData event = new EventBusRefreshData();
                event.setTag(EventBusRefreshData.tag);
                event.setError(true);
                EventBus.getDefault().post(event);
                if (isSaveByUser) {
                    dimsDialog();
                    finish();
                }
            }
        },false);
    }



    private void showContentTipDialog(String rightBtnText,String tip){
        DoubleBtnTiptDialog doubleBtnLongTextDialog = new DoubleBtnTiptDialog(NovelCreateContentTosActivity.this,
                R.style.updateDialog, tip, rightBtnText, () -> {
                    NovelEditManager.getInstance().deleteByDBId(tempDbId);
                    finish();
                });
        doubleBtnLongTextDialog.show();
    }


    private boolean checkContent() {
        if (!isDataChange()) {
            return true;
        }
        String content = edContent.getText().toString();
        if (isNullContent(content)) {
            showContentTipDialog("确定并退出","因章节内容为空，当前章节无法创建或保存为草稿。");
            return false;
        }
        return true;
    }

    public void sendNovelOnclick(View v) {
        //隐藏先审后发对话框
//        if (!TextUtils.isEmpty(timer_note) && idChecked<=0) {
//            PublishTipSingleBtnDialog dialog = new PublishTipSingleBtnDialog(NovelCreateContentTosActivity.this, R.style.updateDialog,  timer_note);
//            dialog.show();
//            dialog.setOnClickBtn(() -> {
//                SimpleWeexActivity.startActivity(this,"vue/personalcenter/TFIDCardCertification.js");
//                dialog.dismiss();
//            });
//        }else
//        if(needSetAuthorInfo){
//            toastInformationDialog();
//        }else{
            sendNovel();
//        }
    }


    private void sendNovel() {

        mTitle = edTitle.getText().toString();
        mContent = edContent.getText().toString();
        if (isNullContent(mTitle)) {
            UIUtil.toastMessage(this, "标题不能为空");
            return;
        }
        if (isNullContent(mContent)) {
            UIUtil.toastMessage(this, "内容不为空");
            return;
        }
        if(DiaobaoUtil.getStringSizeNoSpace(mTitle) > 30){
            UIUtil.toastMessage(this, "标题不能超过30字");
            return;
        }
        if (DiaobaoUtil.getStringSizeNoNull(mContent) > 10000) {

            Toast.makeText(NovelCreateContentTosActivity.this, "单章不要超过1万字哦~", Toast.LENGTH_SHORT).show();
            return;
        }

        TipInfo info = new TipInfo();
        info.setTipListener(tipListener);
        if (nvoelFlag == NovelEditManager.NOVEL_DRAFTS) {// 草稿
            if (novelBean != null && novelBean.getDescription() != null && novelBean.getDescription().getArticle_id() != null) {
                info.setTitle("修改成功");
            } else {
                info.setTitle("发布章节");
            }
        } else if (nvoelFlag == NovelEditManager.NOVEL_SECTION) {// 已发布章节
            info.setTitle("修改成功");
        } else if (nvoelFlag == NovelEditManager.NOVEL_CREATE) {// 新建章节
            info.setTitle("发布章节");
        }
        boolean needRequest = SharedPreferenceUtil.getProtocolDialog(this, AccountService.getInstance().getUserUid(), String.valueOf(Constant.OBJECT_TYPE_NOVEL));
//        showDialog();
        if (needRequest) {
            // 拉请求问后台要不要权限
            HomeMainServices.getInstance().getProtocolRequest(this, String.valueOf(Constant.OBJECT_TYPE_NOVEL));
            // 根据后台要求是否弹出窗口
        } else {
            // 直接发布
            saveContent(TimeUtil.getNowTimeTo(TimeUtil.TIME_FORMAT),true);
//            NovelCreateServices.getInstance().saveNovelChapter(NovelCreateContentTosActivity.this, NovelCreateContentTosActivity.this, getObjectId(), getSendArticleId(), mTitle, mContent, isWeiboSelected, mAuthorSay,getDraftsId());
            setResult(NewNovelCreateListTosActivity.REFRESH_RESULT_CODE);
        }
    }

    private void initData(Serializable serializable, int flag) {
        if (flag == NovelEditManager.NOVEL_DRAFTS) {// 草稿
            novelBean = (NovelDraftBean) serializable;
            isUnSync = novelBean.isBackupUnSync();
            if (novelBean.getDescription() != null) {
                edTitle.setText(novelBean.getDescription().getArticle_title());
                edTitle.setSelection(edTitle.getText().length());
                mAuthorSay = novelBean.getExtral_text();
                if (novelBean.getDbId()>0){
                    localDBid = novelBean.getDbId();
                    if (novelBean.getContent() != null && !TextUtils.isEmpty(novelBean.getContent().getText())) {
                        edContent.setText(novelBean.getContent().getText());
                        mPerformEdit.setDefaultText(novelBean.getContent().getText());
                    }
                }else{
                    isAutoSava = false;
                    NovelCreateServices.getInstance().loadDraftUnitContent(this, novelBean.getId());// 请求草稿详情
                    isAutoSava = false;
                    ctrlWaitDialong(true);
                }

            }
            if(novelBean.getUser() != null && !TextUtils.isEmpty(novelBean.getUser().getIcon())){
                GlideUtil.displayCircleImage(imgHead,novelBean.getUser().getIcon());
            }
        } else if (flag == NovelEditManager.NOVEL_SECTION) {// 已发布章节
            bean = (HomeTopBean) serializable;
            edTitle.setText(bean.getTitle());
            // 拉取小说内容
            String novelUnitId = bean.getId();

            isAutoSava = false;
            NovelCreateServices.getInstance().loadNovelUnitContent(this, novelUnitId, "write");// 请求发布章节详情
            isAutoSava = false;
            ctrlWaitDialong(true);
            edTitle.setSelection(edTitle.getText().length());
            if(bean != null && !TextUtils.isEmpty(bean.getIcon_url())){
                GlideUtil.displayCircleImage(imgHead,bean.getIcon_url());
            }
        } else if (flag == NovelEditManager.NOVEL_CREATE) {// 创建章节
            bean = (HomeTopBean) serializable;
            if(bean != null && !TextUtils.isEmpty(bean.getIcon_url())){
                GlideUtil.displayCircleImage(imgHead,bean.getIcon_url());
            }
        }
    }

    /**
     * 控制等待窗口的开关
     *
     * @param open true时打开等待窗口
     */
    private void ctrlWaitDialong(boolean open) {
        try{
            if (contentWaitDialog != null) {
                if (open) {
                    contentWaitDialog.show();
                } else {
                    contentWaitDialog.cancel();
                }
            } else {
                contentWaitDialog = new WaitDialog(this, R.style.updateDialog);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void saveDraftsOnclick(View v) {
        if (novelBean!=null && novelBean.getDescription() != null) {
            //草稿状态下点击保存按钮
            TMAnalysis.event(this, "novel_content_save_on_draft");
        }else{
            //已发布状态下点击保存按钮
            TMAnalysis.event(this, "novel_content_save_on_formal");
        }
        saveDraftUpdateUI(true);

    }

    private NovelEditModel buildModel(String title,String content,boolean clickPublish) {
        NovelEditModel node = new NovelEditModel();
        node.setNovel_id(getObjectId());
        node.setCreated_at(System.currentTimeMillis()/1000);
        node.setId(localDBid);
        if (nvoelFlag == NovelEditManager.NOVEL_SECTION) {
            if (getArticleId() != null) {
                node.setChapter_id(getArticleId());
            } else if (bean.getArticle_id() != null) {
                node.setChapter_id(bean.getArticle_id());
            }
        } else if (nvoelFlag == NovelEditManager.NOVEL_CREATE) {
            node.setChapter_id("-1");
        }else{
            node.setChapter_id(getDraftsId());
        }

        if (!TextUtils.isEmpty(publish) && publish.equals("1")) {
            if (clickPublish) {
                node.setFlag(nvoelFlag);
            }else{
                node.setFlag(NovelEditManager.NOVEL_SECTION);
            }
        }else{
            node.setFlag(nvoelFlag);
        }
        node.setTempDbId(tempDbId);
        node.setUid(AccountService.getInstance().getUserUid());
        node.setTitle(title);
        node.setContent(content);
        node.setAuthor_say(mAuthorSay);
        return node;
    }

    private void saveDraft(boolean isSaveByUser,NovelEditManager.OnResult onResult,boolean clickPublishBtn) {
        String title = edTitle.getText().toString();
        String content = edContent.getText().toString();
        isClosePage = true;
        if (isSaveByUser){
            if (localCheck(title, content)) {
                showDialog();
                NovelEditManager.getInstance().uploadData(buildModel(title,content,clickPublishBtn), onResult, isUploadDataRepeat(title,content,mAuthorSay),isSaveByUser);
            }
        }else{
            if (isDataChange()||isUnSync){
                NovelEditManager.getInstance().uploadData(buildModel(title,content,clickPublishBtn), onResult, isUploadDataRepeat(title,content,mAuthorSay),isSaveByUser);
            }
        }

    }

    /**
     * 根据最后一次上传的内容判断是否需要再次存入本地数据库
     * 主要目的在于去重，否则有可能在本地生成较多的重复数据
     * @param nTitle
     * @param nContent
     * @param nAuthorSay
     * @return
     */
    private boolean isUploadDataRepeat(String nTitle, String nContent, String nAuthorSay) {
        boolean isRepeat;
        if (!TextUtils.isEmpty(nTitle) && !nTitle.equals(lastSaveTitle) ||
                !TextUtils.isEmpty(nContent) && !nContent.equals(lastSaveContent) ||
                !TextUtils.isEmpty(nAuthorSay) && !nAuthorSay.equals(lastSaveAuthorSay)) {
            isRepeat = false;
        }else{
            isRepeat = true;
        }
        lastSaveTitle = nTitle;
        lastSaveContent = nContent;
        lastSaveAuthorSay = nAuthorSay;
        return isRepeat;
    }


    /**
     * 根据最后一次保存的  临时数据  判断是否需要再次存入本地数据库
     * 主要目的在于减少不必要的数据库操作
     * @param nTitle
     * @param nContent
     * @param nAuthorSay
     * @return
     */
    private boolean isTempDataRepeat(String nTitle, String nContent, String nAuthorSay) {
        boolean isRepeat;
        if(!TextUtils.isEmpty(nContent) && !nContent.equals("\u3000\u3000") && !nContent.equals(lastTempContent)){
            isRepeat = false;
        }else{
            isRepeat = true;
        }
        lastTempTitle = nTitle;
        lastTempContent = nContent;
        lastTempAuthorSay = nAuthorSay;
        return isRepeat;
    }

    public void redo(View view) {
        mPerformEdit.redo();
    }



    /**
     * 定时发送
     * */
    private void  saveContent(String date,boolean clickPublishBtn){
        if(StringUtil.stringLength(date)){
            isTimeSent = true ;
        }else {
            isTimeSent = false ;
        }
        String title = edTitle.getText().toString();
        String content = edContent.getText().toString();
        if (localCheck(title, content)) {
            if (nvoelFlag != NovelEditManager.NOVEL_CREATE) {
                saveDraft(false,null,clickPublishBtn);
            }
            savaDraftsHttp(title, content ,date,clickPublishBtn);
        }
    }


    private boolean localCheck(String title,String content) {
        if (isNullContent(content)) {
            Toast.makeText(NovelCreateContentTosActivity.this, "小说内容不能为空噢！", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (DiaobaoUtil.getStringSizeNoNull(content) > 10000) {
            Toast.makeText(NovelCreateContentTosActivity.this, "单章不要超过1万字哦~", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (isNullContent(title)) {
            Toast.makeText(NovelCreateContentTosActivity.this, "请输入标题！", Toast.LENGTH_SHORT).show();
            return false;
        }

        if(DiaobaoUtil.getStringSizeNoSpace(mTitle) > 30){
            Toast.makeText(NovelCreateContentTosActivity.this, "标题不能超过30字！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }



    public void saveTimeDraftsOnclick(View view){
//        if (!TextUtils.isEmpty(timer_note) && idChecked<=0) {
//            PublishTipSingleBtnDialog dialog = new PublishTipSingleBtnDialog(NovelCreateContentTosActivity.this, R.style.updateDialog,  timer_note);
//            dialog.show();
//            dialog.setOnClickBtn(() -> {
//                SimpleWeexActivity.startActivity(this,"vue/personalcenter/TFIDCardCertification.js");
//                dialog.dismiss();
//            });
//        }else if(needSetAuthorInfo){
//            toastInformationDialog();
//        }else{
            saveTimeDrafts();
//        }
    }

    private AppCompatDialog ad;
    private void toastInformationDialog() {
        ad = new AppCompatDialog(this);
        ad.setContentView(R.layout.dialog_update_information);
        View layClose = ad.findViewById(R.id.layClose);
        layClose.setOnClickListener(v -> ad.dismiss());
        EditText etQQ = ad.findViewById(R.id.etQQ);
        EditText etPhone = ad.findViewById(R.id.etPhone);
        View tvSure = ad.findViewById(R.id.tvSure);
        tvSure.setOnClickListener(v->{
            setAuthorInfo(etQQ.getText().toString(),etPhone.getText().toString());
        });
        ad.show();
    }

    private void setAuthorInfo(String qq,String phone){
        if (qq!=null && !qq.isEmpty()){
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("qq_num",qq);
                jsonObject.put("phone_num",phone);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String format = AesUtil.encrypt(jsonObject.toString(), getKey(), getVector());
            ApiClient.getInstance().apiService.setAuthorInfo(format)
                    .compose(RxJavaHelper.observeOnMainThread(this))
                    .subscribe(new BaseSubscriber<BaseResponseBean<AuthorInfoBean>>(){
                        @Override
                        public void onNext(BaseResponseBean<AuthorInfoBean> bean) {
                            super.onNext(bean);
                            if (bean != null && bean.getData() != null && bean.getData().isRes()) {
                                //设置成功
                                ad.dismiss();
                                needSetAuthorInfo = false;
                                Toast.makeText(NovelCreateContentTosActivity.this,"设置成功",Toast.LENGTH_LONG).show();

                            }else{
                                //设置失败
                                Toast.makeText(NovelCreateContentTosActivity.this,"设置失败，请重试",Toast.LENGTH_LONG).show();
                            }
                        }
                    });
        }else{
            Toast.makeText(this,"请输入QQ号码",Toast.LENGTH_LONG).show();
        }
    }

    private String getKey() {
        String key = "openapi@doufu.la";
        return key;
    }

    private String getVector() {
        String vector = "kingreader@doufu";
        return vector;
    }

    private void saveTimeDrafts() {
        NovelCreateSentTimeDialog timeDialog = new NovelCreateSentTimeDialog();
        timeDialog.setSureSentListener(date -> saveContent(date,false));
        timeDialog.show(getFragmentManager(),"timeDialog");
    }


    private void savaDraftsHttp(String title, String content ,String date,boolean publish) {
        if (!isAutoSava || isTimeSent) {
            showDialog();
        }
        JSONObject object = new JSONObject();
        try {
            object.put("object_type", Constant.OBJECT_TYPE_NOVEL + "");
            object.put("article_title", title);
            object.put("text", content);
            object.put("draftType", "3");
            object.put("object_id", getObjectId());

            if (getArticleId() != null) {
                object.put("article_id", getArticleId());
            } else if (nvoelFlag == NovelEditManager.NOVEL_SECTION && bean.getArticle_id() != null) {
                object.put("article_id", bean.getArticle_id());
            }

            if (chapterId!=null && !chapterId.equals("")) {
                object.put("chapter_id", chapterId);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        String mcontent = object.toString();
        object.remove("text");
        String des = object.toString();

        NovelCreateServices.getInstance().loadSaveNovelDrafts(this, getObjectId(), getDraftsId(), mcontent, des, mAuthorSay,date,publish);
    }

    private boolean isNullContent(String content) {
        return content == null || "".equals(content)||"\u3000\u3000".equals(content)||"\u3000".equals(content);
    }

    private void showDialog() {
        dialog = new WaitDialog(this, R.style.updateDialog);
        dialog.show();
    }

    private void dimsDialog() {
        if (!isFinishing() && dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private String getObjectId() {
        String objectId = null;
        if (nvoelFlag == NovelEditManager.NOVEL_DRAFTS && novelBean != null && novelBean.getDescription() != null) {
            objectId = novelBean.getObject_id();
        } else if (nvoelFlag == NovelEditManager.NOVEL_SECTION && bean != null) {
            objectId = bean.getTopicId();
        } else if (nvoelFlag == NovelEditManager.NOVEL_CREATE && bean != null) {
            objectId = bean.getId();
        }
        return objectId;
    }

    private String getDraftsId() {
        String draftsId = null;
        if (nvoelFlag == NovelEditManager.NOVEL_DRAFTS) {
            draftsId = novelBean.getId();
        }
        return draftsId;
    }

    private String getSendArticleId() {
        String articleId = null;
        if (nvoelFlag == NovelEditManager.NOVEL_DRAFTS) {
            if (novelBean.getDescription() != null) {
                articleId = novelBean.getDescription().getArticle_id();
                if (novelids != null) {
                    if (!novelids.contains(articleId)) {
                        articleId = null;
                    }
                }
            }
        } else if (nvoelFlag == NovelEditManager.NOVEL_SECTION) {
            articleId = bean.getId();
        }
        return articleId;
    }


    private String getArticleId() {
        String articleId = null;
        if (nvoelFlag == NovelEditManager.NOVEL_DRAFTS) {
            if (novelBean.getDescription() != null) {
                articleId = novelBean.getDescription().getArticle_id();
            }
            if (TextUtils.isEmpty(articleId)){
                articleId = novelBean.getId();
            }
        } else if (nvoelFlag == NovelEditManager.NOVEL_SECTION) {
            articleId = bean.getId();
        }

        return articleId;
    }

    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        ctrlWaitDialong(false);
        mHandler.sendEmptyMessage(0);
        switch (handleType) {
            case NovelCreateServices.HANDLE_TYPE_SEND_NOVEL:
                if (response.getStatus() == 0 && response.getFail_code() == 0) {
                    //如果是从存稿中发布则删除存稿
                    if (getDraftsId() != null) {
                        NovelCreateServices.getInstance().loadDelDrafts(this, getDraftsId());
                    }
                    try{
                        JSONObject data = (JSONObject) response.getData();
                        if (data.has("status") && data.getInt("status") == 10 &&
                                data.has("msg") && !TextUtils.isEmpty(data.getString("msg"))){
                            String tip = data.getString("msg");
                            String title = "发布失败";
                            if (data.has("title") && !TextUtils.isEmpty(data.getString("title"))) {
                                title = data.getString("title");
                            }
                            DoubleBtnLongTextDialog doubleBtnLongTextDialog = new DoubleBtnLongTextDialog(NovelCreateContentTosActivity.this,
                                    R.style.updateDialog, tip, title, () -> NovelCreateServices.getInstance().saveNovelChapter(NovelCreateContentTosActivity.this, NovelCreateContentTosActivity.this, getObjectId(),
                                            getSendArticleId(), mTitle, mContent, isWeiboSelected, mAuthorSay,true,getDraftsId()));
                            doubleBtnLongTextDialog.show();
                        }else{
                            if (data != null && data.has("msg")) {
                                NovelEditManager.getInstance().deleteByDBId(tempDbId);
                                if (data.has("article_id") && data.getInt("article_id") > 0 && nvoelFlag == NovelEditManager.NOVEL_SECTION) {
                                    NovelEditModel model = buildModel(initTitle,initContent,false);
                                    model.setChapter_id(String.valueOf(data.getInt("article_id")));
                                    model.setFlag(NovelEditManager.NOVEL_SECTION);
                                    NovelEditManager.getInstance().uploadData(model, null, false,false);
                                }

                                UIUtil.toastMessage(NovelCreateContentTosActivity.this, data.getString("msg"));
                            }
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                } else if(response.getStatus() == -1 && !TextUtils.isEmpty(response.getUser_msg())){
                    SingleBtnDialog dialog = new SingleBtnDialog(NovelCreateContentTosActivity.this, R.style.updateDialog, response.getUser_msg(), "发布失败");
                    dialog.show();
                } else {
                    UIUtil.toastMessage(NovelCreateContentTosActivity.this, DiaobaoUtil.getErrorTips(response));
                }
                break;
            case NovelCreateServices.HANDLE_TYPE_SAVE_DRAFTS:
                if (DiaobaoUtil.isRequestResult(response)) {
                    if(isTimeSent){
                        UIUtil.toastMessage(NovelCreateContentTosActivity.this, "发布成功");
                    }else {
                        UIUtil.toastMessage(NovelCreateContentTosActivity.this, "存稿成功");
                    }
                    NovelEditManager.getInstance().deleteByDBId(tempDbId);
                    NovelCreateBean novelBean = new NovelCreateBean();
                    novelBean.setJson2((JSONObject) response.getData());
                    setResult(NewNovelCreateListTosActivity.REFRESH_RESULT_CODE);
                    finish();
                } else {
                    SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, R.style.updateDialog,
                            DiaobaoUtil.getErrorTips(response), "提示","知道了");
                    singleBtnDialog.show();
                }
                break;
            case NovelCreateServices.HANDLE_TYPE_GET_NOVEL_CONTENT:
                if (DiaobaoUtil.isRequestResult(response)) {
                    JSONObject jsonObject = (JSONObject) response.getData();
                    if (response.getStatus() == Constant.STATUS_SUCCESS) {
                        // details
                        JSONObject detail;
                        try {
                            detail = jsonObject.getJSONObject("detail");
                            boolean canSaveAs = jsonObject.getBoolean("canSaveAs");
                            if (canSaveAs){
                                ivSave.setVisibility(View.VISIBLE);
                            }else{
                                ivSave.setVisibility(View.GONE);
                            }
                            contentBean = new HomeTopBean();
                            contentBean.setJson(detail);
                            chapterId = contentBean.getId();
                            edContent.setText(contentBean.getDes());
                            mPerformEdit.setDefaultText(contentBean.getDes());
                            mAuthorSay = contentBean.getExtral_text();
                            isAutoSava = true;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    UIUtil.toastMessage(NovelCreateContentTosActivity.this, DiaobaoUtil.getErrorTips(response));
                }
                break;
            case NovelCreateServices.HANDLE_TYPE_GET_DRAFT_CONTENT:
                if (DiaobaoUtil.isRequestResult(response)) {
                    NovelDraftBean draftBean = new NovelDraftBean();
                    JSONObject data = (JSONObject) response.getData();
                    if (data != null && data.has("draft")) {
                        try {
                            JSONObject draft = data.getJSONObject("draft");
                            draftBean.setJson2(draft);
                            chapterId = draftBean.getContent().getChapter_id();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    String severLastTime = draftBean.getUpdated_at();
                    NovelEditModel localModel = NovelEditManager.getInstance().getLastLocalDataByChapterId(getObjectId(), getDraftsId());
                    if (localModel!=null && !TextUtils.isEmpty(localModel.getContent()) && TimeDateFunction.getTimeToLong(severLastTime) < localModel.getCreated_at()){
                        //使用本地数据
                        edContent.setText(localModel.getContent());
                        initTitle = localModel.getTitle();
                        edTitle.setText(initTitle);
                        mPerformEdit.setDefaultText(localModel.getContent());
                        mAuthorSay = localModel.getAuthor_say();
                    }else{
                        if (draftBean.getContent() != null) {
                            edContent.setText(draftBean.getContent().getText());
                            mPerformEdit.setDefaultText(draftBean.getContent().getText());
                            mAuthorSay = draftBean.getExtral_text();
                        }
                    }
                    isAutoSava = true;

                } else {
                    NovelEditModel localModel = NovelEditManager.getInstance().getLastLocalDataByChapterId(getObjectId(), getDraftsId());
                    if (localModel!=null && !TextUtils.isEmpty(localModel.getContent())){
                        //使用本地数据
                        edContent.setText(localModel.getContent());
                        initTitle = localModel.getTitle();
                        edTitle.setText(initTitle);
                        mPerformEdit.setDefaultText(localModel.getContent());
                        mAuthorSay = localModel.getAuthor_say();
                        isAutoSava = true;
                    }
                    UIUtil.toastMessage(NovelCreateContentTosActivity.this, DiaobaoUtil.getErrorTips(response));
                }
                break;
            // 是否弹出协议
            case HomeMainServices.HANDLE_TYPE_NEED_PROTOCOL: {
                JSONObject data = (JSONObject) response.getData();
                if (data.has("need") && data.has("license") && data.has("url")) {
                    try {
                        String isNeed = data.getString("need");
                        if (isNeed != null && isNeed.equals("true")) {
                            // 打开协议弹窗
                            ProtocolDialog dialog = new ProtocolDialog();
                            dialog.setOnResultListener(tipListener);
                            dialog.setContentStr(data.getString("license"));
                            dialog.setProtocolWebUrl(data.getString("url"));
                            dialog.show(getFragmentManager(), "");
                        } else {
                            // 直接发布
                            saveContent(TimeUtil.getNowTimeTo(TimeUtil.TIME_FORMAT),true);
//                            NovelCreateServices.getInstance().saveNovelChapter(NovelCreateContentTosActivity.this, NovelCreateContentTosActivity.this,
//                                    getObjectId(), getSendArticleId(), mTitle, mContent, isWeiboSelected, mAuthorSay,getDraftsId());
                            setResult(NewNovelCreateListTosActivity.REFRESH_RESULT_CODE);
                            SharedPreferenceUtil.saveProtocolDialog(NovelCreateContentTosActivity.this, AccountService.getInstance().getUserUid(), String.valueOf(Constant.OBJECT_TYPE_NOVEL));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
            }
            default:
                break;
        }
        initTitle = edTitle.getText().toString();
        initContent = edContent.getText().toString();
        initAuthorSay = mAuthorSay;
    }

    public void onFormatData(View view) {
        formatAllContent(edContent,edContent.getText().toString());
    }


    public void undo(View view) {
        mPerformEdit.undo();
    }

    private void formatAllContent(EditText edContent, String content){
        if (!TextUtils.isEmpty(content)) {
            //先去掉空格
            content = content.replace("\u3000","");
            content = content.replace("\t", "");
            content = content.replace("\r", "\n");
            //去掉多余的换行
            while (content.contains("\n\n")) {
                content = content.replace("\n\n","\n");
            }
            //按照换行去拆分字符串
            String[] tempArray = content.split("\n");
            if (tempArray != null && tempArray.length > 0) {
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < tempArray.length; i++) {
                    String temp = tempArray[i].trim();
                    if (TextUtils.isEmpty(temp)) {
                        //文章头部有换行，则去掉
                        continue;
                    }
                    stringBuilder.append("\u3000\u3000").append(temp);
                    if (i < tempArray.length - 1) {
                        stringBuilder.append("\n");
                    }
                }
                edContent.setText(stringBuilder.toString());
                edContent.clearFocus();
                UIUtil.hideCurrentSoftInput(this);
                Toast.makeText(this, "已排版", Toast.LENGTH_LONG).show();
            }

        }
    }

    private ResultTipListener tipListener = (flag, type) -> {
        if (flag == 1) {
//                showDialog();
            SharedPreferenceUtil.saveProtocolDialog(NovelCreateContentTosActivity.this, AccountService.getInstance().getUserUid(), String.valueOf(Constant.OBJECT_TYPE_NOVEL));
            saveContent(TimeUtil.getNowTimeTo(TimeUtil.TIME_FORMAT),true);
//                NovelCreateServices.getInstance().saveNovelChapter(NovelCreateContentTosActivity.this, NovelCreateContentTosActivity.this, getObjectId(), getSendArticleId(), mTitle, mContent, isWeiboSelected, mAuthorSay,getDraftsId());
            setResult(NewNovelCreateListTosActivity.REFRESH_RESULT_CODE);
        }
    };

    /**
     * 内容是否发生改变
     * @param newTitle 新的标题
     * @param newContent 新的内容
     * @return true改变，false不变
     */
    private boolean isContentChange(String newTitle, String newContent) {
        if (newTitle == null || newContent == null) {
            return false;
        }
        if (DiaobaoUtil.getStringSizeNoSpace(newTitle) < 1 && DiaobaoUtil.getStringSizeNoSpace(newContent) < 1) {
            return false;
        }
        return !newTitle.equals(initTitle) || !newContent.equals(initContent);
    }

    /**
     * 作者有话说是否改变
     * @return true改变，false不变
     */
    private boolean isAuthorSay(){
        if(TextUtils.isEmpty(mAuthorSay)){
            return false;
        }
        return !mAuthorSay.equals(initAuthorSay);
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            dimsDialog();
        }
    };





    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EditNovelThemeHelper.clearTheme();
        EventBus.getDefault().unregister(this);
        if(timer != null){
            timer.cancel();
            timer = null;
        }
    }

    /**
     * 数据是否改变
     */
    private boolean isDataChange() {
        if((isContentChange(edTitle.getText().toString(), edContent.getText().toString())) || isAuthorSay()){
            return true;
        }
        return false;
    }


    private long tempDbId;

    /**
     * 保存临时数据，防止应用崩溃导致数据丢失
     */
    private void saveTempData() {
        if (isClosePage) {
            return;
        }
        String title = edTitle.getText().toString();
        String content = edContent.getText().toString();
        if (isDataChange() && !isTempDataRepeat(title,content,mAuthorSay)) {
            NovelEditModel novelEditModel = buildModel(title,content,false);
            novelEditModel.setState(1);  //临时数据
            NovelEditManager.getInstance().saveTempData(novelEditModel, l -> tempDbId = l);

        }
    }



    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llHistory:
                Intent intentHistory = new Intent();
                intentHistory.setClass(this, NovelEditHistoryActivity.class);
                intentHistory.putExtra(NovelEditHistoryActivity.INTENT_KEY_NOVEL_ID, getObjectId());
                intentHistory.putExtra(NovelEditHistoryActivity.INTENT_KEY_CHAPTER_ID, getArticleId());
                startActivity(intentHistory);
                break;
            case R.id.muneScreen:
                setMuneVisiable(false);
                break;
            case R.id.llThemeSet:
                setMuneVisiable(true);
                break;
            case R.id.llDayAndNight:
                int type;
                if (EditNovelThemeHelper.getEditNovelTheme().getThemeType() == ThemeType.TYPE_NIGHT) {
                    type = ThemeType.TYPE_DAY;
                }else{
                    type = ThemeType.TYPE_NIGHT;
                }
                starAnimation(type);
                break;
            case R.id.tvAuthorSay:
                Intent intent = new Intent(this, NovelCreateContentAuthorActivity.class);
                intent.putExtra(SAY_CONTENT, mAuthorSay);
                if(novelBean != null && novelBean.getUser() != null && !TextUtils.isEmpty(novelBean.getUser().getIcon())){
                    intent.putExtra(Constant.IMAGE, novelBean.getUser().getIcon());
                }else if(bean != null && !TextUtils.isEmpty(bean.getIcon_url())){
                    intent.putExtra(Constant.IMAGE, bean.getIcon_url());
                }
                startActivityForResult(intent, REQUEST_CODE_SAY_CONTENT);
                break;
            case R.id.llSysLight:
                isSysLight = !isSysLight;
                if (isSysLight) {
                    DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_EDIT_NOVEL_PAGE_SYS_LIGHT,true,this);
                    tvSysLight.setTextColor(getResources().getColor(EditNovelThemeHelper.getEditNovelTheme().getMenuTheme().getSysLightFCSelect()));
                    ScreenBrightnessUtil.setBrightness(this,-1);
                }else{
                    DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_EDIT_NOVEL_PAGE_SYS_LIGHT,false,this);
                    tvSysLight.setTextColor(getResources().getColor(EditNovelThemeHelper.getEditNovelTheme().getMenuTheme().getSysLightFCUnSelect()));
                    int light = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_EDIT_NOVEL_PAGE_LIGHT_STATE, this, 10);
                    seekbarLight.setProgress(light);
                    ScreenBrightnessUtil.setBrightness(this,light);
                }
                break;
            case R.id.llFontSizeSub:
                changeFontSizeSeekBar(false);
                break;
            case R.id.llFontSizeAdd:
                changeFontSizeSeekBar(true);
                break;
            case R.id.llLightSub:  //降低亮度
                if (seekbarLight == null) {
                    return;
                }
                int progress1 = seekbarLight.getProgress();
                if (progress1 > 0) {
                    progress1--;
                }
                seekbarLight.setProgress(progress1);
                isSysLight = false;
                tvSysLight.setTextColor(getResources().getColor(EditNovelThemeHelper.getEditNovelTheme().getMenuTheme().getSysLightFCUnSelect()));
                DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_EDIT_NOVEL_PAGE_SYS_LIGHT, false, NovelCreateContentTosActivity.this);

                break;
            case R.id.llLightAdd:  //增强亮度
                if (seekbarLight == null) {
                    return;
                }
                int progress = seekbarLight.getProgress();
                if (progress < 255) {
                    progress++;
                }
                seekbarLight.setProgress(progress);
                isSysLight = false;
                tvSysLight.setTextColor(getResources().getColor(EditNovelThemeHelper.getEditNovelTheme().getMenuTheme().getSysLightFCUnSelect()));
                DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_EDIT_NOVEL_PAGE_SYS_LIGHT, false, NovelCreateContentTosActivity.this);
                break;
            default:
                break;
        }
    }

    private boolean isWeiboSelected = false;


    @Override
    public void finish() {
        saveWeiboState();
        super.finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        WeiboService.getInstance().sinaAuthorizeCallBack(requestCode, resultCode, data);
        if(resultCode == RESULT_CODE_SAY_CONTENT && data != null){
            // 获取作者想说的内容
            mAuthorSay = data.getStringExtra(SAY_CONTENT);

        }
    }

    private String lastContentChange;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {


        int nCount = DiaobaoUtil.getStringSizeNoNull(s.toString());
        if (nCount > 10000 && !TextUtils.isEmpty(lastContentChange) && s.toString().length()>lastContentChange.length()) {
            edContent.setText(lastContentChange);
            edContent.setSelection(lastContentChange.length());
            Toast.makeText(this,"内容不能超过10000字",Toast.LENGTH_LONG).show();
        }else{
            tvContentCount.setText(nCount+"字");
            lastContentChange = edContent.getText().toString();
            if (nCount >= 10000 && mPerformEdit!=null && !TextUtils.isEmpty(lastContentChange)) {
                mPerformEdit.clearHistory();
            }
            if (DiaobaoUtil.getStringSizeNoSpace(s.toString()) > 0) {
                tvHint.setVisibility(View.GONE);
            }else{
                tvHint.setVisibility(View.VISIBLE);
            }
        }

    }


    /**
     * 获取敏感词列表
     */
    private void getSensitiveWordList() {
        if (highSensitive != null && highSensitive.size() > 0 && littleSensitive != null && highSensitive.size() > 0) {
            return;
        }
        ApiClient.getInstance().getService().getRiskWords()
                .compose(RxJavaHelper.<RiskWordGson>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<RiskWordGson>(){
                    @Override
                    public void onNext(RiskWordGson riskWordGson) {
                        super.onNext(riskWordGson);
                        if (riskWordGson != null && riskWordGson.getData() != null) {
                            if (riskWordGson.getData().getHigh_risk_words() != null) {
                                highSensitive = riskWordGson.getData().getHigh_risk_words();
                            }
                            if (riskWordGson.getData().getWords() != null) {
                                littleSensitive = riskWordGson.getData().getWords();
                            }
                        }
                    }
                });
    }


    private static List<String> highSensitive = new ArrayList<>();
    private static List<String> littleSensitive = new ArrayList<>();


    public void sensitiveWorld(View view) {
        setSensitiveWords(edContent.getText().toString());
    }


    class MySpanWatcher implements SpanWatcher{

        @Override
        public void onSpanAdded(Spannable text, Object what, int start, int end) {
        }

        @Override
        public void onSpanRemoved(Spannable text, Object what, int start, int end) {
        }

        @Override
        public void onSpanChanged(Spannable text, Object what, int ostart, int oend, int nstart, int nend) {
            if ((what ==Selection.SELECTION_END||what == Selection.SELECTION_START) && ostart != nstart) {
                BackgroundColorSpan[] spans = text.getSpans(nstart, nend, BackgroundColorSpan.class);
                if (spans != null) {
                    for (int i = 0; i < spans.length; i++) {
                        text.removeSpan(spans[i]);
                    }
                }
            }
        }
    }

    /**
     * 设置敏感词高亮显示
     */
    private void setSensitiveWords(final String content) {
        if (littleSensitive.size() == 0 && highSensitive.size() == 0) {
            //敏感词库没有下载下来
            return;
        }
        Observable.create((Observable.OnSubscribe<SpannableStringBuilder>) subscriber -> {
            SpannableStringBuilder spannableString = new SpannableStringBuilder();
            spannableString.append(content);
            for (int i = 0; i < littleSensitive.size(); i++) {
                String word = littleSensitive.get(i);
                int index = spannableString.toString().indexOf(word);
                if ( index > -1) {
                    BackgroundColorSpan littleSpan = new BackgroundColorSpan(Color.parseColor("#feeb6e"));
                    spannableString.setSpan(littleSpan,index,index+word.length(),Spannable.SPAN_PRIORITY);
                    while (index > -1) {
                        index = spannableString.toString().indexOf(word, index + word.length());
                        if (index > -1) {
                            BackgroundColorSpan littleSpan2 = new BackgroundColorSpan(Color.parseColor("#feeb6e"));
                            spannableString.setSpan(littleSpan2,index,index+word.length(),Spannable.SPAN_PRIORITY);
                        }
                    }
                }
            }
            for (int i = 0; i < highSensitive.size(); i++) {
                String word = highSensitive.get(i);
                int index = content.indexOf(word);
                if ( index > -1) {
                    BackgroundColorSpan highSpan = new BackgroundColorSpan(Color.parseColor("#fe6e6e"));
                    spannableString.setSpan(highSpan, index, index + word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    while (index > -1) {
                        index = spannableString.toString().indexOf(word,index+word.length());
                        if (index > -1) {
                            BackgroundColorSpan highSpan2 = new BackgroundColorSpan(Color.parseColor("#fe6e6e"));
                            spannableString.setSpan(highSpan2,index,index+word.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                    }
                }
            }
            subscriber.onNext(spannableString);
        })
        .compose(RxJavaHelper.<SpannableStringBuilder>observeOnMainThread(this))
        .subscribe(new BaseSubscriber<SpannableStringBuilder>(){
            @Override
            public void onNext(SpannableStringBuilder spannableString) {
                super.onNext(spannableString);
                edContent.clearFocus();
                edContent.setText(spannableString);
                Toast.makeText(NovelCreateContentTosActivity.this,"敏感词检测完毕！",Toast.LENGTH_LONG).show();
            }
        });

    }

    @Override
    public void afterTextChanged(Editable s) {
    }



    public boolean isMuneVisiable = false;
    /**
     * 显示/隐藏 二级菜单
     * @param visiable
     */
    public void setMuneVisiable(boolean visiable){
        if (rlTheme != null && isMuneVisiable != visiable){
            // 0是底部框，1是顶部框
            ObjectAnimator[] objectAnimators = new ObjectAnimator[1];
            AnimatorSet animatorSet = new AnimatorSet();
            // 出现
            if (visiable) {
                muneScreen.setVisibility(View.VISIBLE);
                rlTheme.setVisibility(View.VISIBLE);
                objectAnimators[0] = ObjectAnimator.ofFloat(rlTheme, "translationY", com.taptech.doufu.util.ScreenUtil.getScreenHeight(this), 0);
            }
            // 隐藏
            else {
                muneScreen.setVisibility(View.GONE);
                objectAnimators[0] = ObjectAnimator.ofFloat(rlTheme, "translationY", 0, com.taptech.doufu.util.ScreenUtil.getScreenHeight(this) - ScreenUtil.dip2px(this,48));
            }
            try{
                animatorSet.setDuration(500);
                animatorSet.playTogether(objectAnimators);
                animatorSet.start();
                isMuneVisiable = visiable;
            }catch (AndroidRuntimeException e){
                e.printStackTrace();
            }
        }
    }


    private void setListen() {
        llLightSub.setOnClickListener(this);
        llSysLight.setOnClickListener(this);
        llLightAdd.setOnClickListener(this);
        llFontSizeSub.setOnClickListener(this);
        llFontSizeAdd.setOnClickListener(this);

        QLXNotificationCenter.getInstance().addNotify("TFIDCheckNotify", this, (event, data) -> getTips());

        SoftKeyboardUtil.observeSoftKeyboard(this, (softKeybardHeight, visible) -> {
            if (visible) {
                layPunctuation.setVisibility(View.VISIBLE);
            }else{
                layPunctuation.setVisibility(View.GONE);
            }
        });

        int progress = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_EDIT_NOVEL_PAGE_LIGHT_STATE,
                this, ScreenBrightnessUtil.getScreenBrightness(this));
        isSysLight = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_EDIT_NOVEL_PAGE_SYS_LIGHT,
                this, true);
        if (isSysLight) {
            ScreenBrightnessUtil.setBrightness(this, -1);
            tvSysLight.setTextColor(getResources().getColor(EditNovelThemeHelper.getEditNovelTheme().getMenuTheme().getSysLightFCSelect()));
        }else{
            ScreenBrightnessUtil.setBrightness(this, progress);
            tvSysLight.setTextColor(getResources().getColor(EditNovelThemeHelper.getEditNovelTheme().getMenuTheme().getSysLightFCUnSelect()));
        }
        seekbarLight.setProgress(progress);
        seekbarLight.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                ScreenBrightnessUtil.setBrightness(NovelCreateContentTosActivity.this, progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSysLight = false;
                tvSysLight.setTextColor(getResources().getColor(EditNovelThemeHelper.getEditNovelTheme().getMenuTheme().getSysLightFCUnSelect()));
                DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_EDIT_NOVEL_PAGE_SYS_LIGHT, false, NovelCreateContentTosActivity.this);
                DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SharedPreferencesKey.SP_EDIT_NOVEL_PAGE_LIGHT_STATE,
                        seekBar.getProgress(),NovelCreateContentTosActivity.this);

            }
        });

        int fontProgress = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_EDIT_NOVEL_PAGE_FONT_SIZE_STATE,
                this,1);
        seekbarFontSize.setProgress(fontProgress);
        updateTextSize(progressToFontSize(fontProgress));
        seekbarFontSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }


            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                updateTextSize(progressToFontSize(seekBar.getProgress()));
                DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SharedPreferencesKey.SP_EDIT_NOVEL_PAGE_FONT_SIZE_STATE,
                        seekBar.getProgress(),getThisActivity());
            }
        });

        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recycleView.setLayoutManager(manager);
        adapter = new EditNovelThemeAdapter(this, EditNovelThemeHelper.getEditNovelTheme(),this);
        recycleView.setAdapter(adapter);
    }


    private void resetBackup(NovelEditModel model) {
        if (model == null) {
            Toast.makeText(NovelCreateContentTosActivity.this,"数据异常，恢复失败",Toast.LENGTH_LONG).show();
            return;
        }
        final String nTitle = model.getTitle();
        final String nContent = model.getContent();
        long id = model.getId();
        String currTitle = edTitle.getText().toString();
        String currContent = edContent.getText().toString();
        NovelEditManager.getInstance().resetBackup(buildModel(currTitle,currContent,false),
                id, new NovelEditManager.OnResult() {
                    @Override
                    public void onSuccess() {
                        lastContentChange = "";
                        edContent.setText(nContent);
                        edTitle.setText(nTitle);
                        Toast.makeText(NovelCreateContentTosActivity.this,"恢复成功",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onError(String msg) {
                        if (!TextUtils.isEmpty(msg)){
                            Toast.makeText(NovelCreateContentTosActivity.this,msg,Toast.LENGTH_LONG).show();
                        }else{
                            Toast.makeText(NovelCreateContentTosActivity.this,"恢复失败",Toast.LENGTH_LONG).show();
                        }
                    }

                });

    }

    @Override
    public void onClickItem(Integer themeType) {
        if (EditNovelThemeHelper.getEditNovelTheme().getThemeType() == themeType) {
            return;
        }
        setPageTheme(EditNovelThemeHelper.updataEditNovelTheme(themeType));
    }



    private void setPageTheme(EditNovelTheme editNovelTheme) {

        //设置顶部栏
        ivBack.setImageResource(editNovelTheme.getTopBarTheme().getBackImage());
        ivFormat.setImageResource(editNovelTheme.getTopBarTheme().getFormatImage());
        ivSensitive.setImageResource(editNovelTheme.getTopBarTheme().getSensitiveImage());
        ivClock.setImageResource(editNovelTheme.getTopBarTheme().getClockImage());
        ivSave.setImageResource(editNovelTheme.getTopBarTheme().getSaveImage());
        topVerticalLine.setBackgroundResource(editNovelTheme.getTopBarTheme().getVerticalLineImage());
        titleLayout.setBackgroundResource(editNovelTheme.getTopBarTheme().getBgColor());
        tvContentCount.setTextColor(getResources().getColor(editNovelTheme.getTopBarTheme().getFontGrayColor()));
        tvSend.setTextColor(getResources().getColor(editNovelTheme.getTopBarTheme().getFontRedColor()));

        if (canUndo) {
            ivUndo.setImageResource(EditNovelThemeHelper.getEditNovelTheme().getTopBarTheme().getUndoSelectImage());
        }else{
            ivUndo.setImageResource(EditNovelThemeHelper.getEditNovelTheme().getTopBarTheme().getUndoImage());
        }
        if (canRedo) {
            ivRedo.setImageResource(EditNovelThemeHelper.getEditNovelTheme().getTopBarTheme().getRedoSelectImage());
        }else{
            ivRedo.setImageResource(EditNovelThemeHelper.getEditNovelTheme().getTopBarTheme().getRedoImage());
        }



        //设置底部栏
        lineBottom.setBackgroundColor(getResources().getColor(editNovelTheme.getLineColor()));
        bottomBar.setBackgroundResource(editNovelTheme.getBottomBarTheme().getBgColor());
        imgHead.setAlpha(editNovelTheme.getBottomBarTheme().getAlpha());
        tvAuthorSay.setBackgroundResource(editNovelTheme.getBottomBarTheme().getAuthorSayImage());
        tvAuthorSay.setTextColor(getResources().getColor(editNovelTheme.getBottomBarTheme().getFontGrayColor()));
        tvSet.setTextColor(getResources().getColor(editNovelTheme.getBottomBarTheme().getFontGrayColor()));
        tvHistory.setTextColor(getResources().getColor(editNovelTheme.getBottomBarTheme().getFontGrayColor()));
        tvNight.setTextColor(getResources().getColor(editNovelTheme.getBottomBarTheme().getFontGrayColor()));
        ivSet.setImageResource(editNovelTheme.getBottomBarTheme().getSetImage());
        ivHistory.setImageResource(editNovelTheme.getBottomBarTheme().getHistoryImage());
        ivNight.setImageResource(editNovelTheme.getBottomBarTheme().getNightImage());



        //设置菜单栏
        ivLightSub.setImageResource(editNovelTheme.getMenuTheme().getLowLightImage());
        ivLightAdd.setImageResource(editNovelTheme.getMenuTheme().getHighLightImage());
        ivFontSizeSub.setImageResource(editNovelTheme.getMenuTheme().getSubFontSizeImage());
        ivFontSizeAdd.setImageResource(editNovelTheme.getMenuTheme().getAddFontSizeImage());
        rlTheme.setBackgroundColor(getResources().getColor(editNovelTheme.getMenuTheme().getBgColor()));
        llSysLight.setBackgroundResource(editNovelTheme.getMenuTheme().getSysLightBg());
        if (isSysLight) {
            tvSysLight.setTextColor(getResources().getColor(editNovelTheme.getMenuTheme().getSysLightFCSelect()));
        }else{
            tvSysLight.setTextColor(getResources().getColor(editNovelTheme.getMenuTheme().getSysLightFCUnSelect()));
        }
        seekbarFontSize.setProgressDrawable(getResources().getDrawable(editNovelTheme.getSeekBarProgressColor()));
        seekbarLight.setProgressDrawable(getResources().getDrawable(editNovelTheme.getSeekBarProgressColor()));
        seekbarFontSize.setThumb(getResources().getDrawable(editNovelTheme.getSeekBarImage()));
        seekbarLight.setThumb(getResources().getDrawable(editNovelTheme.getSeekBarImage()));
        seekbarFontSize.setThumbOffset(ScreenUtil2.dip2px(10));
        seekbarLight.setThumbOffset(ScreenUtil2.dip2px(10));

        //设置编辑栏
        llParent.setBackgroundResource(editNovelTheme.getContentBg());
        lineTitle.setBackgroundColor(getResources().getColor(editNovelTheme.getLineColor()));
        lineContent.setBackgroundColor(getResources().getColor(editNovelTheme.getLineColor()));
        edTitle.setTextColor(getResources().getColor(editNovelTheme.getContentFontColor()));
        edContent.setTextColor(getResources().getColor(editNovelTheme.getContentFontColor()));
        edTitle.setHintTextColor(getResources().getColor(editNovelTheme.getHintColor()));
        edContent.setHintTextColor(getResources().getColor(editNovelTheme.getHintColor()));
        tvHint.setTextColor(getResources().getColor(editNovelTheme.getHintColor()));

        layPunctuation.setBackgroundColor(getResources().getColor(editNovelTheme.getPunctuationTheme().getBgColor()));
        linePunctuation.setBackgroundColor(getResources().getColor(editNovelTheme.getPunctuationTheme().getLineColor()));
        ivHidePunctuation.setImageResource(editNovelTheme.getPunctuationTheme().getKeyboardImage());

        recycleView.setAlpha(editNovelTheme.getMenuTheme().getThemeListAlpha());
        if (adapter != null) {
            adapter.updata(editNovelTheme);
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        //进入后台
        saveTempData();
    }

    private void updateTextSize(int fontSize) {
        edContent.setTextSize(fontSize);
    }

    private int progressToFontSize(int progress) {
        int fontSize;
        if (progress == 0) {
            fontSize = 15;
        }else if(progress == 1){
            fontSize = 17;
        }else if(progress == 2){
            fontSize = 19;
        } else if (progress == 3) {
            fontSize = 21;
        } else if (progress == 4) {
            fontSize = 23;
        }else{
            fontSize = 25;
        }
        return fontSize;
    }

    private void changeFontSizeSeekBar(boolean isAdd) {
        if (seekbarFontSize != null) {
            if (isAdd) {
                if (seekbarFontSize.getMax() > seekbarFontSize.getProgress()) {
                    seekbarFontSize.setProgress(seekbarFontSize.getProgress()+1);
                }
            }else {
                if (seekbarFontSize.getProgress()>0) {
                    seekbarFontSize.setProgress(seekbarFontSize.getProgress()-1);
                }
            }
            updateTextSize(progressToFontSize(seekbarFontSize.getProgress()));
            DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SharedPreferencesKey.SP_EDIT_NOVEL_PAGE_FONT_SIZE_STATE,
                    seekbarFontSize.getProgress(),getThisActivity());
        }
    }


    private boolean canClick = true;
    private void starAnimation(int themeType) {


        if (!canClick) {
            return;
        }

        canClick = false;
        int oldThemeType = EditNovelThemeHelper.getEditNovelTheme().getThemeType();
        int oldBg = EditNovelThemeHelper.getEditNovelTheme().getContentBg();
        int oldMenuBg = EditNovelThemeHelper.getEditNovelTheme().getMenuTheme().getBgColor();
        int oldLineBg = EditNovelThemeHelper.getEditNovelTheme().getLineColor();
        final EditNovelTheme editNovelTheme = EditNovelThemeHelper.updataEditNovelTheme(themeType);
        if (adapter != null) {
            adapter.updata(editNovelTheme);
        }
        final Timer timer = new Timer();
        if (oldThemeType == ThemeType.TYPE_DAY || oldThemeType == ThemeType.TYPE_AQUA ||
                oldThemeType == ThemeType.TYPE_BLUE ||oldThemeType == ThemeType.TYPE_BUFF||
                oldThemeType == ThemeType.TYPE_NIGHT || oldThemeType == ThemeType.TYPE_RED) {
            try {
                setAnimationColor(titleLayout,getResources().getColor(oldMenuBg),getResources().getColor(editNovelTheme.getTopBarTheme().getBgColor()),2000);
                setAnimationColor(bottomBar,getResources().getColor(oldMenuBg),getResources().getColor(editNovelTheme.getBottomBarTheme().getBgColor()),2000);
                setAnimationColor(rlTheme,getResources().getColor(oldMenuBg),getResources().getColor(editNovelTheme.getMenuTheme().getBgColor()),2000);
                setAnimationColor(llParent,getResources().getColor(oldBg),getResources().getColor(editNovelTheme.getContentBg()),2000);
                setAnimationColor(lineBottom,getResources().getColor(oldLineBg),getResources().getColor(editNovelTheme.getLineColor()),2000);
                setAnimationColor(lineContent,getResources().getColor(oldLineBg),getResources().getColor(editNovelTheme.getLineColor()),2000);
                setAnimationColor(lineTitle,getResources().getColor(oldLineBg),getResources().getColor(editNovelTheme.getLineColor()),2000);
                setAnimationAlpha(seekbarFontSize,1.0f,0.0f,300);
                setAnimationAlpha(seekbarLight,1.0f,0.0f,300);
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setPageTheme(editNovelTheme);
                                try {
                                    setAnimationAlpha(seekbarFontSize,0.0f,1.0f,300);
                                    setAnimationAlpha(seekbarLight,0.0f,1.0f,300);
                                    timer.schedule(new TimerTask() {
                                        @Override
                                        public void run() {
                                            canClick = true;
                                        }
                                    },2000);
                                } catch (NoSuchMethodError e) {
                                    canClick = true;
                                }
                            }
                        });
                    }
                },100);
            } catch (NoSuchMethodError e) {
                setPageTheme(editNovelTheme);
                canClick = true;
            }
        }else{
            canClick = true;
            setPageTheme(editNovelTheme);
        }

    }

    public static void setAnimationColor(final View view, int starColor, int endColor,long time)throws NoSuchMethodError  {
        ValueAnimator valueAnimator = ValueAnimator.ofArgb(starColor, endColor);
        valueAnimator.addUpdateListener(animation -> {
            int color = (int) animation.getAnimatedValue();
            if (view != null) {
                view.setBackgroundColor(color);
            }
        });
        valueAnimator.setRepeatCount(0);
        valueAnimator.setDuration(time);
        valueAnimator.start();
    }


    public static void setAnimationAlpha(final View view,float start,float end,long time)throws NoSuchMethodError  {
        try {
            ValueAnimator valueAnimator = ValueAnimator.ofFloat(start, end);
            valueAnimator.addUpdateListener(animation -> {
                float alpha = (float) animation.getAnimatedValue();
                if (view != null) {
                    view.setAlpha(alpha);
                }
            });
            valueAnimator.setRepeatCount(0);
            valueAnimator.setDuration(time);
            valueAnimator.start();
        } catch (NoSuchMethodError e) {

        }
    }
}
